package cn.wolfcode.mq;

import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.redis.SeckillRedisKey;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 订单15分钟后查看用户是否支付, 若还未支付,结束订单,回补库存
 */
@Component
@RocketMQMessageListener(
        consumerGroup = "MQOrderTimeOutListener31",
        topic = MQConstant.ORDER_PAY_TIMEOUT_TOPIC,
        selectorType = SelectorType.TAG,
        selectorExpression = "tag"
)
@Slf4j
public class MQOrderTimeOutListener implements RocketMQListener<String> {

    // 使用 canal 技术, 已经将订单的创建和修改同步到redis中,故查询可以直接在redis中查

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private IOrderInfoService orderInfoService;

    @Override
    public void onMessage(String orderNo) {
        log.info("进入到延迟订单验证的消费者中了...");
        // 1.查询当前订单状态是否为支付状态
        Object orderJson = redisTemplate.opsForHash().get(SeckillRedisKey.SECKILL_ORDER_HASH.getRealKey(""), orderNo);
        if (orderJson == null){
            return;
        }
        OrderInfo orderInfo = JSON.parseObject(orderJson.toString(), OrderInfo.class);
        if (OrderInfo.STATUS_ACCOUNT_PAID.equals(orderInfo.getStatus())) {
            return ;
        }
        // 2.查看当前订单状态, 若为 未付款 状态,
        if (OrderInfo.STATUS_ARREARAGE.equals(orderInfo.getStatus())) {
            // 3.回补真是库存
            seckillProductService.incrStockCount(orderInfo.getSeckillId());
            // 4. 回补预库存
            seckillProductService.asysBackRedisStockCount(orderInfo.getSeckillId(),orderInfo.getSeckillTime());

            // 5.修改本地标识
            rocketMQTemplate.sendOneWay(MQConstant.CANCEL_SECKILL_OVER_SIGE_TOPIC,orderInfo.getOrderNo());
            // 6修改订单状态
            orderInfoService.updateCancelStatus(orderInfo.getOrderNo(), OrderInfo.STATUS_TIMEOUT);
        }



    }
}
